import React, { useEffect } from 'react';
import { Navigate, useNavigate } from 'react-router-dom';

import localINFO from '@/utils/localInfo';

interface AuthRouteProps {
  children: React.ReactNode;
  auth: number[];
}

const AuthRoute: React.FC<AuthRouteProps> = ({ children, auth }) => {
  const navigate = useNavigate();
  const role = localINFO.getRoleId(); // role: 1/2/3 超级管理员/管理员/操作员

  useEffect(() => {
    if (!role) {
      navigate('/login');
    }
  }, [role, navigate]);

  const isAuthorized = role !== undefined && auth.includes(role);

  return isAuthorized ? <>{children}</> : <Navigate replace to="/404" />;
};

export default AuthRoute;
